//
//  SearchAddressDictionaryView.swift
//  GreenDeal
//
//  Created by Moennig Q on 27/2/2023.
//

import UIKit

enum SearchAddressDictionaryType: Int{
    case postcode = 0
    case streetType
    case unitType
}
class SearchAddressDictionaryView: UIView {
    private var type: SearchAddressDictionaryType = .unitType
    private var defaultSearchValue: String = ""
    //
    var selectClosure: ((PhysicalAddressViewModel?)->Void)?
    let searchTextfield = DIYTextField()
    let tableView = TableView()
    var list = [PhysicalAddressViewModel]()
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 17))
    var showPleaseSleectFlag: Bool = false
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(_ type: SearchAddressDictionaryType,showPleaseSleectFlag: Bool, title: String, defaultSearchValue: String ) {
        super.init(frame: CGRect.zero)
        self.type = type
        self.defaultSearchValue = defaultSearchValue
        self.titleLabel.text = title
        self.showPleaseSleectFlag = showPleaseSleectFlag
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        let backView = UIView()
        backView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(40)
            make.left.right.bottom.equalToSuperview()
        }
        //modelSelectLabel
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.centerX.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //Done btn
        let closeBtn = UIButton()
        closeBtn.setImage(R.image.me_presentvc_close(), for: UIControl.State.normal)
        backView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.width.height.equalTo(40)
            make.centerY.equalTo(titleLabel)
        }
        let searchBackView = UIView()
        searchBackView.backgroundColor = UIColor(hexStr: "#F5F5F5")
        backView.addSubview(searchBackView)
        searchBackView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
            make.height.greaterThanOrEqualTo(0)
            make.left.right.equalToSuperview()
        }
        
        searchTextfield.placeholder = R.string.localizable.search()
        searchTextfield.showLeftImageView("edit_address_search_icon")
        searchBackView.addSubview(searchTextfield)
        searchTextfield.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(40)
            make.bottom.equalTo(-12)
        }
        //
        backView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchBackView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //
        searchTextfield.delegate = self
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SearchAddressDictionaryCell.self, forCellReuseIdentifier: SearchAddressDictionaryCell.reuseCellIdentifier)
        //
        closeBtn.addTarget(self, action: #selector(closeBtnClick), for: UIControl.Event.touchUpInside)
        
        searchTextfield.addTarget(self, action: #selector(textFieldEditChanged(_:)), for: UIControl.Event.editingChanged)
        //
        if self.defaultSearchValue != ""{
            searchTextfield.text = self.defaultSearchValue
        }
        self.loadData(self.defaultSearchValue)
    }
    
    @objc func textFieldEditChanged(_ textField: UITextField){
        self.loadData(textField.text ?? "")
    }
    @objc func closeBtnClick(){
        self.selectClosure?(nil)
        self.removeFromSuperview()
    }
    func loadData(_ queryStr: String){
        switch type {
        case .unitType:
            self.list = DBManager.shared.getUnitTypeList(queryStr)
            //unit type是非必填项，允许选择为空
            if self.showPleaseSleectFlag {
                let firstRow =  PhysicalAddressViewModel()
                firstRow.unit_type =  ""
                firstRow.unit_type_name = R.string.localizable.pleaseSelect()
                self.list.insert(firstRow, at: 0)
            }
        case .streetType:
            self.list = DBManager.shared.getStreetTypeList(queryStr)
            //unit type是非必填项，允许选择为空
            if self.showPleaseSleectFlag {
                let firstRow =  PhysicalAddressViewModel()
                firstRow.street_type =  ""
                firstRow.street_type_name = R.string.localizable.pleaseSelect()
                self.list.insert(firstRow, at: 0)
            }
        case .postcode:
            self.list = DBManager.shared.getSuburbListByPostcode(queryStr)
        }
        self.tableView.reloadData()
        //没有数据显示not data view，有数据隐藏not data view
        self.tableView.showResultView(nodataFlag: self.list.count == 0 ? true : false)
    }
}
extension SearchAddressDictionaryView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchAddressDictionaryCell.reuseCellIdentifier) as? SearchAddressDictionaryCell
        if cell == nil {
            cell = SearchAddressDictionaryCell(style: .default, reuseIdentifier: SearchAddressDictionaryCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row],type: self.type)
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectClosure?(self.list[indexPath.row])
        self.removeFromSuperview()
    }
}
